package com.zhongkai.service.impl;

import com.mysql.jdbc.StringUtils;
import com.zhongkai.Bean.PageBean;
import com.zhongkai.CryptoUtil;
import com.zhongkai.app.service.AppHomeUnitService;
import com.zhongkai.app.service.IBaseDao;
import com.zhongkai.app.service.PageQuerDao;
import com.zhongkai.jedis.JedisClient;
import com.zhongkai.model.utils.TTHelp;
import com.zhongkai.model.utils.ZhongkaiResult;
import com.zhongkai.model3.*;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * APP首页
 */

@Service
@Transactional(rollbackFor = Exception.class)
public class AppHomeUnitServiceImpl implements AppHomeUnitService {

    @Autowired
    private IBaseDao iBaseDao;


    @Autowired
    private PageQuerDao pageQuerDao;


    @Autowired
    private JedisClient jedisClient;

    /**
     * 获取用户设备列表
     *
     * @param app_uuid 用户uuid
     */

    @Override
    public ZhongkaiResult appUnitList(String app_uuid) {
        if (StringUtils.isNullOrEmpty(app_uuid)) {
            return ZhongkaiResult.build(500, "数据不完整");
        }

        List<FsonUser> list = iBaseDao.find("from FsonUser su where su.appUuid='" + app_uuid + "'");

        for (FsonUser fsonUser : list) {
            //fsonUser.getfUid()
            SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + fsonUser.getfUid() + "'"); //验证设备
            fsonUser.setUnit = setUnit;

            setUnit = null;
        }

        return ZhongkaiResult.ok(list);
    }

    @Override
    public ZhongkaiResult appUnitListRole(String app_uuid) {
        if (StringUtils.isNullOrEmpty(app_uuid)) {
            return ZhongkaiResult.build(500, "数据不完整");
        }

        List<FsonUser> list = iBaseDao.find("from FsonUser su where su.appUuid='" + app_uuid + "' and su.appRole=3");

        return ZhongkaiResult.ok(list);
    }


    /**
     * 添加39.100.237.119
     *
     * @param app_uuid    用户uuid
     * @param unit_uiid   机组uuid
     * @param phone       子用户用户手机号
     * @param code        验证码
     * @param name        姓名
     * @param relation_id 关系列表id
     */
    @Override
    public ZhongkaiResult addUnitSon(String app_uuid, String unit_uiid, String phone, String code, String name, Integer relation_id) {
        if (
                StringUtils.isNullOrEmpty(app_uuid) || StringUtils.isNullOrEmpty(unit_uiid) ||
                        StringUtils.isNullOrEmpty(phone) || StringUtils.isNullOrEmpty(code) ||
                        StringUtils.isNullOrEmpty(name) || relation_id == 100
                ) {
            return ZhongkaiResult.build(500, "数据不完整");
        }


        FsonUser fsonUser1 = (FsonUser) iBaseDao.get("from FsonUser su where su.appUuid='" + app_uuid + "' or su.fUid='" + unit_uiid + "'");

      //  FsonUser fsonUser2 = (FsonUser) iBaseDao.get("from FsonUser su where su.fUuid='" + app_uuid + "' or su.appPhone='" + phone + "'");

/*        if (fsonUser2 != null) {
            return ZhongkaiResult.build(500, "您是户主,不可添加自己为子用户");
        }*/


        AppRole appRole = (AppRole) iBaseDao.get("from AppRole su where su.roleName='户主用户'");

        AppRole sonRole = (AppRole) iBaseDao.get("from AppRole su where su.roleName='子用户'");

        AppRelation appRelation = (AppRelation) iBaseDao.get("from AppRelation su where su.id=" + relation_id);

        if (appRole == null) {
            return ZhongkaiResult.build(500, "户主权限缺失,请联系管理员");
        }

        if (sonRole == null) {
            return ZhongkaiResult.build(500, "子用户权限缺失,请联系管理员");
        }

        if (fsonUser1 == null) {
            return ZhongkaiResult.build(500, "您名下没有可操控的设备");
        }

        if (appRelation == null) {
            return ZhongkaiResult.build(500, "用户关系不存在");
        }


        if (fsonUser1.getAppRole() != appRole.getId()) {
            return ZhongkaiResult.build(500, "您不是户主用户");
        }

        String jedcode = null;
        try {
            jedcode = jedisClient.get(phone);
        } catch (Exception e) {
            e.printStackTrace();
            return ZhongkaiResult.build(500, "redis连接获取失败");
        }


        if (!code.equals(jedcode)) {
            return ZhongkaiResult.build(400, "验证码错误");
        }


        AppUser appUser = (AppUser) iBaseDao.get("from AppUser tb where tb.appPhone='" + phone + "'");

        if (app_uuid.equals(appUser.getAppUuid())) {
            return ZhongkaiResult.build(500, "不可添加自己为子用户");
        }


        if (appUser == null) { //用户不存在 创建
            appUser = new AppUser();

            String c_uuid = TTHelp.generate();

            appUser.setAppUuid(c_uuid);  //设置用户uid

            appUser.setAppPhone(phone);   //用户手机号

            appUser.setAppName(name);     //用户姓名

            appUser.setAppImg("http://111.61.64.62:8001/group1/M00/00/01/wKgZhV3krh2AaPVDAAQqKpbszHg957.jpg");
            appUser.setAppSex("1");
            long millis = new DateTime().getMillis(); //获取当前系统时间戳
            appUser.setAppTime(millis);
            appUser.setAppRemove("1");
            appUser.setAppVice("子用户"); //设置权限
            appUser.setAppViceId(2); //设置权限 子用户
            //加密
            String pass = CryptoUtil.encode64(CryptoUtil.SALT, "123456");

            appUser.setAppPassword(pass); //设置加密后的密码


            appUser.setAppRemove("1");  //1正常  2 删除
            //   appUser.setAppVice("2"); //是否为维修用户 1是 2否
/*                    appUser.setAppViceId(sonRole.getId());
                    appUser.setAppVice(sonRole.getRoleName());*/

            iBaseDao.save(appUser);

            FsonUser user_fn = new FsonUser();

            user_fn.setfUid(unit_uiid); //可操控设备的uuid
            user_fn.setAppPhone(phone); //用户手机号
            user_fn.setFatherPhone(fsonUser1.getAppPhone());//父用户手机号如果是户主用户存入0
            user_fn.setAppRole(sonRole.getId());//角色id
            user_fn.setAppUuid(c_uuid);//可操控设备用户的唯一标识
            user_fn.setfUuid(app_uuid);//父用户的唯一标识户主存入0
            user_fn.setSetAlias(fsonUser1.getSetAlias());//设备别名
            user_fn.setUuid(appRelation.getId());  //用户关机id
            user_fn.setRole(appRelation.getName()); //用户关系名称 亲戚 朋友...
            user_fn.setSonName(name);
            iBaseDao.save(user_fn);

            return ZhongkaiResult.ok();

        } else { //用户存在 直接建立关系
            FsonUser user_fn = new FsonUser();

            user_fn.setfUid(unit_uiid); //可操控设备的uuid
            user_fn.setAppPhone(phone); //用户手机号
            user_fn.setFatherPhone(fsonUser1.getAppPhone());//父用户手机号如果是户主用户存入0
            user_fn.setAppRole(sonRole.getId());//角色id
            user_fn.setAppUuid(appUser.getAppUuid());//可操控设备用户的唯一标识
            user_fn.setfUuid(app_uuid);//父用户的唯一标识户主存入0
            user_fn.setSetAlias(fsonUser1.getSetAlias());//设备别名
            user_fn.setUuid(appRelation.getId());  //用户关系id
            user_fn.setRole(appRelation.getName()); //用户关系名称 亲戚 朋友...
            user_fn.setSonName(name);
            iBaseDao.save(user_fn);

            return ZhongkaiResult.ok();
        }


    }

    /**
     * 修改子用户
     *
     * @param phone       子用户手机号
     * @param name        姓名
     * @param relation_id 关系列表id
     * @param fsonid      关系列表id
     */
    @Override
    public ZhongkaiResult updateUnitSon(String phone, String name, Integer relation_id, Integer fsonid) {
        if (
                StringUtils.isNullOrEmpty(phone) ||
                        StringUtils.isNullOrEmpty(name) || relation_id == 0 || fsonid == 0
                ) {
            return ZhongkaiResult.build(500, "数据不完整");
        }

        FsonUser fsonUser1 = (FsonUser) iBaseDao.get("from FsonUser su where su.id=" + fsonid);

        if (fsonUser1 == null) {
            return ZhongkaiResult.build(500, "子用户不存在");
        }

        if (!phone.equals(fsonUser1.getAppPhone())) {

            return ZhongkaiResult.build(500, "无法修改子用户的手机号!如有需要请删除后重新添加");
        }


        AppRelation appRelation = (AppRelation) iBaseDao.get("from AppRelation su where su.id=" + relation_id);

        if (appRelation == null) {
            return ZhongkaiResult.build(500, "用户关系不存在,请联系管理员");
        }

        fsonUser1.setUuid(appRelation.getId());  //用户关系id
        fsonUser1.setRole(appRelation.getName()); //用户关系名称 亲戚 朋友...
        fsonUser1.setSonName(name);

        iBaseDao.update(fsonUser1);

        return ZhongkaiResult.ok();
    }


    /**
     * 删除子用户
     *
     * @param phone    子用户手机号
     * @param app_uuid 父用户uuid
     */
    @Override
    public ZhongkaiResult removeUnitSon(String app_uuid, String phone) {

        if (StringUtils.isNullOrEmpty(app_uuid) || StringUtils.isNullOrEmpty(phone)) {
            return ZhongkaiResult.build(500, "数据不完整");
        }

        FsonUser fsonUser1 = (FsonUser) iBaseDao.get("from FsonUser su where su.appPhone='" + phone + "' or su.fUuid='" + app_uuid + "'");


        if (fsonUser1 == null) {
            return ZhongkaiResult.build(500, "子用户不存在");
        }


        iBaseDao.delete(fsonUser1);
        return ZhongkaiResult.ok();
    }


    /**
     * 亲戚关系列表
     */
    @Override
    public ZhongkaiResult relationList() {
        List list = iBaseDao.find("from AppRelation");

        return ZhongkaiResult.ok(list);
    }


    /**
     * 子用户列表
     *
     * @param app_uuid 用户uuid
     */
    @Override
    public ZhongkaiResult unitSonList(String app_uuid, Integer page, Integer rows) {
        if (page == 0 || rows == 0 || StringUtils.isNullOrEmpty(app_uuid)) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(FsonUser.class);
        detachedCriteria.add(Restrictions.eq("fUuid", app_uuid)); //增加条件 父用户uuid
        pageBean.setDetachedCriteria(detachedCriteria);
        pageQuerDao.pageQuery(pageBean);
        return ZhongkaiResult.ok(pageBean);

    }


    /**
     * 设备托管
     *
     * @param unit_uuid   设备uuid
     * @param trusteeship 托管参数 1取消托管  2托管
     */
    @Override
    public ZhongkaiResult uniTrusteeship(String unit_uuid, String trusteeship) {

        if (StringUtils.isNullOrEmpty(unit_uuid)) {
            return ZhongkaiResult.build(500, "参数不完整");
        }

        if (StringUtils.isNullOrEmpty(trusteeship)) {

            Object o = iBaseDao.get("select trusteeship from SetUnit su where su.setUuid='" + unit_uuid + "'");//验证设备

            if (o == null) {
                return ZhongkaiResult.build(500, "设备不存在");
            }

            return ZhongkaiResult.ok(o);
        }


        SetUnit setUnit = (SetUnit) iBaseDao.get("from SetUnit su where su.setUuid='" + unit_uuid + "'");

        if (setUnit == null) {
            return ZhongkaiResult.build(500, "设备不存在");
        } else if ("2".equals(setUnit.getSetRemove())) {
            return ZhongkaiResult.build(500, "设备已被删除");
        } else if ("1".equals(setUnit.getSetBound())) {
            return ZhongkaiResult.build(500, "该设备未绑定用户");
        } else if (trusteeship.equals(setUnit.getTrusteeship())) {
            if ("1".equals(trusteeship)) {
                return ZhongkaiResult.build(500, "您的设备已经取消托管");

            } else {
                return ZhongkaiResult.build(500, "您的设备已经托管");
            }
        }


        setUnit.setTrusteeship(trusteeship);

        iBaseDao.save(setUnit);
        return ZhongkaiResult.ok();
    }


    /**
     * 报警信息列表
     *
     * @param unit_uuid 设备uuid
     */
    @Override
    public ZhongkaiResult unlikeList(String unit_uuid, Integer page, Integer rows) {
        if (page == 0 || rows == 0 || StringUtils.isNullOrEmpty(unit_uuid)) {
            return ZhongkaiResult.build(400, "数据不完整");
        }


        PageBean pageBean = new PageBean();
        pageBean.setCurrentPage(page);
        pageBean.setPageSize(rows);
        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Unlike.class);
        detachedCriteria.add(Restrictions.eq("unitUuid", unit_uuid)); //增加条件 父用户uuid
        detachedCriteria.addOrder(Order.desc("solveTime")); //根据传入的字段进行升序排序 100 99 ...
        pageBean.setDetachedCriteria(detachedCriteria);
        pageQuerDao.pageQuery(pageBean);
        return ZhongkaiResult.ok(pageBean);
    }


}
